/*
*************************************************************************
*西瑞克斯研发管理系统
*版 本: 1.0   
*日 期：02/11/2012    
*作 者： 王浩 QQ：873987060   
*************************************************************************   
*/ 
package com.manager.workflow.core;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.fireflow.engine.IProcessInstance;
import org.fireflow.engine.IWorkItem;
import org.fireflow.engine.IWorkflowSession;
import org.fireflow.engine.RuntimeContext;
import org.fireflow.engine.definition.WorkflowDefinition;
import org.fireflow.engine.impl.TaskInstance;
import org.fireflow.engine.impl.WorkItem;
import org.fireflow.engine.taskinstance.DynamicAssignmentHandler;
import org.fireflow.model.FormTask;
import org.fireflow.model.Task;
import org.fireflow.model.resource.Form;

import com.manager.commons.page.PageBean;
import com.manager.workflow.WorkFlowConstants;
import com.manager.workflow.dao.WorkItemDAO;
import com.workflowdefinition.YfBussTaskinstance;

/**
 * 工作流相关操作
 * @author 王浩 QQ：873987060   
 *
 */
public class WorkFlowCommon  {
	
	private Logger log = Logger.getLogger(this.getClass());
	
	private RuntimeContext runtimeContext;
	
	private WorkItemDAO workItemDAO;


	public WorkItemDAO getWorkItemDAO() {
		return workItemDAO;
	}

	public void setWorkItemDAO(WorkItemDAO workItemDAO) {
		this.workItemDAO = workItemDAO;
	}
    
	/**
	 * 获取流程实例编号
	 * @return
	 */
	public String getProcessInstanceId(String bussId,String bussType){
		return workItemDAO.getProcessInstanceId(bussId, bussType);
	}
	/**
	 * 启动工作流,创建流程
	 */
	public String startFlow(String workflowProcessName,String createId){
		return startFlow(workflowProcessName,createId,null);
	}
	
	/**
	 * 启动工作流,创建流程
	 */
	public String startFlow(String workflowProcessName,String createId,Map processVariable){
		String processId = null;
		IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
		try {
			IProcessInstance processInstance = workflowSession.createProcessInstance(workflowProcessName,createId);
			if(processVariable!=null){
				processInstance.setProcessInstanceVariables(processVariable);
			}
			processInstance.run();
			processId = processInstance.getId();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("流程启动错误！" + e);
		}
		return processId;
	}
	
	/**
	 * 获得代办工作项目
	 * @return
	 */
	public List getWorkItemList(Map conditionsMap,PageBean pageBean){
		return workItemDAO.getAllWorkItem(conditionsMap, pageBean);
	}
	
	/**
	 * 获得已办工作项目
	 * @return
	 */
	public List getHaveDoneWorkItemList(Map conditionsMap,PageBean pageBean){
		return workItemDAO.getAllHaveDoneWorkItem(conditionsMap, pageBean);
	}
	
	
	/**
	 * 获得代办工作条数
	 * @return
	 */
	public Integer getAllWorkItemCount(Map conditionsMap){
		return workItemDAO.getAllWorkItemCount(conditionsMap);
	}
	
	/**
	 * 获得代办工作条数
	 * @return
	 */
	public Integer getAllWorkItemCountZJL(Map conditionsMap){
		return workItemDAO.getAllWorkItemCountZJL(conditionsMap);
	}
	
	/**
	 * 获得代办工作项目
	 * @return
	 */
	public List getWorkItemListZJL(Map conditionsMap,PageBean pageBean){
		return workItemDAO.getAllWorkItemZJL(conditionsMap, pageBean);
	}
	
	/**
	 * 获得已办工作条数
	 * @return
	 */
	public Integer getAllHaveDoneWorkItemCount(Map conditionsMap){
		return workItemDAO.getAllHaveDoneWorkItemCount(conditionsMap);
	}
	
	/**
	 * 获得任务预警条数
	 * @return
	 */
	public Integer getAllWarnTaskCount(Map queryMap){
		return workItemDAO.getAllWarnTaskCount(queryMap);
	}
	/**
	 * 获得任务预警 
	 * @return
	 */
	public List getAllWarnTask(Map queryMap,final PageBean pageBean){
		return workItemDAO.getAllWarnTask(queryMap, pageBean);
	}
	/**
	 * 获得表单URL和流程变量
	 * @param workItemId
	 * @return
	 * @throws Exception
	 */
	public String[] getFormUrlAndProcessVar(String workItemId){
		String[] res = new String[6];
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = workflowSession.findWorkItemById(workItemId);
			if (workItem != null && workItem.getState() == IWorkItem.RUNNING) {
				TaskInstance taskInstance = ((TaskInstance) workItem.getTaskInstance());
				Task task = taskInstance.getTask();
				String viewUri = null;
				Form formTask = ((FormTask) task).getViewForm();
				if(formTask!=null){
					viewUri = ((FormTask) task).getViewForm().getUri();
				}
				IProcessInstance processInstance = taskInstance.getAliveProcessInstance();
				if(((FormTask) workItem.getTaskInstance().getTask()).getEditForm()!=null){
					res[0] = ((FormTask) workItem.getTaskInstance().getTask()).getEditForm().getUri();
				}
				res[1] = (String) processInstance.getProcessInstanceVariable("bussId");
				res[2] = (String) processInstance.getProcessInstanceVariable("bussType");
				res[3] = processInstance.getId();
				res[4] = YfWorkFlowDefine.getRoleNameByActivityId(taskInstance.getActivityId());
				res[5] = viewUri;
			}
		} catch (Exception e) {
			log.error("获取表单URL错误！" + e);
		}
		return res;
	}
	
	/**
	 * 根据工作项编号获取业务信息
	 * @return
	 */
	public String[] getBussVar(String workItemId){
		String[] res = new String[3];
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = workflowSession.findWorkItemById(workItemId);
			if (workItem != null && (workItem.getState() == IWorkItem.COMPLETED || workItem.getState() == IWorkItem.CANCELED)) {
				YfBussTaskinstance taskInstance = ((YfBussTaskinstance) workItem.getTaskInstance());
				res[0] = taskInstance.getBussId().toString();
				res[1] = taskInstance.getBussType().toString();
				res[2] = taskInstance.getProcessInstanceId();
			}
		} catch (Exception e) {
			log.error("获取表单URL错误！" + e);
		}
		return res;
	}
	
	/**
	 * 处理流程 完成工作项目
	 * @param workItemId
	 * @param mapVar
	 */
	public void commandFlow(String workItemId,Map mapVar){
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = workflowSession.findWorkItemById(workItemId);
			IProcessInstance processInstance = ((TaskInstance)workItem.getTaskInstance()).getAliveProcessInstance();
        	processInstance.setProcessInstanceVariables(mapVar);
			if (workItem != null && workItem.getState() == IWorkItem.RUNNING) {
				workItem.complete();
			}
		} catch (Exception e) {
			log.error("完成工作项目错误错误！" + e);
		}
	}
	
	/**
	 * 返回当前活动节点的审批角色（为了处理一个人有多个角色，审批时不知道是用那个角色审批的，所以采用这种方式）
	 * @param workItemId
	 * @param mapVar
	 */
	public String getRoleNameByActivityId(String workItemId){
		return getRoleNameByActivityId(workItemId,0);
	}
	
	/**
	 * 返回当前活动节点的审批角色（为了处理一个人有多个角色，审批时不知道是用那个角色审批的，所以采用这种方式）
	 * @param workItemId
	 * @param mapVar
	 */
	public String getRoleNameByActivityId(String workItemId,int type){
		String roleName="";
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = workflowSession.findWorkItemById(workItemId);
			TaskInstance taskInstance = ((TaskInstance)workItem.getTaskInstance());
			if(type == 0){
				roleName = YfWorkFlowDefine.getRoleNameByActivityId(taskInstance.getActivityId());
			}
			if(type == 1){
				roleName = YfWorkFlowDefine.getRoleNameByActivityIdAccp(taskInstance.getActivityId());
			}
			if(type == 2){
				roleName = YfWorkFlowDefine.getRoleNameByActivityIdFEE(taskInstance.getActivityId());
			}
		} catch (Exception e) {
			log.error("获取角色错误！" + e);
		}
		return roleName;
	}
	
	/**
	 * 处理流程 完成工作项目
	 * @param workItemId
	 * @param mapVar
	 */
	public void commandFlowDynamicAssign(String workItemId,Map mapVar,List actorList){
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = workflowSession.findWorkItemById(workItemId);
			DynamicAssignmentHandler dynamic = new DynamicAssignmentHandler();
			dynamic.setActorIdsList(actorList);
			dynamic.setNeedClaim(false);
			workflowSession.setAttribute("dynamicHandler", dynamic);
			IProcessInstance processInstance = ((TaskInstance)workItem.getTaskInstance()).getAliveProcessInstance();
        	processInstance.setProcessInstanceVariables(mapVar);
			if (workItem != null && workItem.getState() == IWorkItem.RUNNING) {
				workItem.complete();
			}
		} catch (Exception e) {
			log.error("完成工作项目错误错误！" + e);
		}
	}
	
	/**
	 * 处理流程 打回修改
	 * @param workItemId
	 * @param mapVar
	 */
	public void commandFlowReback(String workItemId,Map mapVar,int type){
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = (WorkItem) workflowSession.findWorkItemById(workItemId);
			TaskInstance taskInstance = ((TaskInstance)workItem.getTaskInstance());
			IProcessInstance processInstance = taskInstance.getAliveProcessInstance();
			/**
			 * 获得上一活动id 
			 */
			String activityId = YfWorkFlowDefine.getPreActivityId(taskInstance.getActivityId(),type);
        	processInstance.setProcessInstanceVariables(mapVar);
			if (workItem != null && workItem.getState() == IWorkItem.RUNNING) {
				workItem.jumpToEx(activityId, null,"打回修改");
			}
		} catch (Exception e) {
			log.error("完成工作项目错误错误！" + e);
		}
	}
	
	/**
	 * 处理流程 打回修改(费用流程)
	 * @param workItemId
	 * @param mapVar
	 */
	public void commandFlowRebackFEE(String workItemId,Map mapVar,int type){
		try {
			IWorkflowSession workflowSession = runtimeContext.getWorkflowSession();
			IWorkItem workItem = (WorkItem) workflowSession.findWorkItemById(workItemId);
			TaskInstance taskInstance = ((TaskInstance)workItem.getTaskInstance());
			IProcessInstance processInstance = taskInstance.getAliveProcessInstance();
			/**
			 * 获得上一活动id 
			 */
			String activityId = YfWorkFlowDefine.getPreActivityIdFEE(taskInstance.getActivityId(),type);
        	processInstance.setProcessInstanceVariables(mapVar);
			if (workItem != null && workItem.getState() == IWorkItem.RUNNING) {
				workItem.jumpToEx(activityId, null,"打回修改");
			}
		} catch (Exception e) {
			log.error("完成工作项目错误错误！" + e);
		}
	}
	
	public YfBussTaskinstance getYfBussTaskinstance(String taskInstanceId){
		return workItemDAO.getYfBussTaskinstance(taskInstanceId);
	}
	
	/**
	 * 处理流程 打回修改
	 * @param workItemId
	 * @param mapVar
	 */
	public void commandFlowReback(String workItemId,Map mapVar){
		commandFlowReback(workItemId,mapVar,YfWorkFlowDefine.START_XMJL);
	}
	
 
	
	public void setRuntimeContext(RuntimeContext runtimeContext) {
		this.runtimeContext = runtimeContext;
	}
}
